//package com.mce.nebula.controller;
//
//import com.mce.nebula.dto.ApiResponse;
//import com.mce.nebula.dto.TeamCreateRequest;
//import com.mce.nebula.dto.TeamResponse;
//import com.mce.nebula.dto.TeamUserResponse;
//import com.mce.nebula.entity.Team;
//import com.mce.nebula.entity.TeamUser;
//import com.mce.nebula.entity.User;
//import com.mce.nebula.repository.UserRepository;
//import com.mce.nebula.security.UserDetailsImpl;
//import com.mce.nebula.service.TeamService;
//import io.swagger.v3.oas.annotations.Operation;
//import io.swagger.v3.oas.annotations.tags.Tag;
//import jakarta.validation.Valid;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.http.ResponseEntity;
//import org.springframework.security.access.prepost.PreAuthorize;
//import org.springframework.security.core.Authentication;
//import org.springframework.web.bind.annotation.*;
//
//import java.util.List;
//import java.util.Map;
//import java.util.stream.Collectors;
//
///**
// * 团队管理控制器
// */
//@Slf4j
//@RestController
//@RequestMapping("/api/teams")
//@Tag(name = "团队管理", description = "团队管理相关接口")
//@RequiredArgsConstructor
//public class TeamController {
//
//    private final TeamService teamService;
//    private final UserRepository userRepository;
//
//    @PostMapping
//    @Operation(summary = "创建团队", description = "创建新团队")
//    public ResponseEntity<ApiResponse<TeamResponse>> createTeam(
//            @Valid @RequestBody TeamCreateRequest request,
//            Authentication authentication) {
//        try {
//            // 从认证信息中获取用户ID
//            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
//            Integer userId = userDetails.getId().intValue();
//
//            Team team = teamService.createTeam(request, userId);
//            return ResponseEntity.ok(ApiResponse.success(new TeamResponse(team), "团队创建成功"));
//        } catch (Exception e) {
//            log.error("Failed to create team: {}", request.getTenantName(), e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
//
//    @GetMapping("/{teamName}")
//    @Operation(summary = "获取团队详情", description = "根据团队名称获取团队详情")
//    public ResponseEntity<ApiResponse<TeamResponse>> getTeam(@PathVariable String teamName) {
//        try {
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            return ResponseEntity.ok(ApiResponse.success(new TeamResponse(team)));
//        } catch (Exception e) {
//            log.error("Failed to get team: {}", teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
//
//    @GetMapping("/{teamName}/overview")
//    @Operation(summary = "团队总览", description = "获取团队总览信息")
//    public ResponseEntity<ApiResponse<Map<String, Object>>> getTeamOverview(@PathVariable String teamName) {
//        try {
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            // 获取团队成员数量
//            List<TeamUser> teamUsers = teamService.getTeamUsers(team.getTenantId());
//
//            Map<String, Object> overview = Map.of(
//                "team", new TeamResponse(team),
//                "memberCount", teamUsers.size(),
//                "isActive", team.getIsActive()
//            );
//
//            return ResponseEntity.ok(ApiResponse.success(overview));
//        } catch (Exception e) {
//            log.error("Failed to get team overview: {}", teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
//
//    @GetMapping("/{teamName}/users")
//    @Operation(summary = "获取团队成员", description = "获取团队成员列表")
//    public ResponseEntity<ApiResponse<List<TeamUserResponse>>> getTeamUsers(@PathVariable String teamName) {
//        try {
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            List<TeamUser> teamUsers = teamService.getTeamUsers(team.getTenantId());
//
//            List<TeamUserResponse> responses = teamUsers.stream()
//                .map(teamUser -> {
//                    User user = userRepository.findById(teamUser.getUserId().longValue()).orElse(null);
//                    return new TeamUserResponse(teamUser, user);
//                })
//                .collect(Collectors.toList());
//
//            return ResponseEntity.ok(ApiResponse.success(responses));
//        } catch (Exception e) {
//            log.error("Failed to get team users: {}", teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
//
//    @PostMapping("/{teamName}/users")
//    @Operation(summary = "添加团队成员", description = "添加用户到团队")
//    @PreAuthorize("hasRole('ADMIN') or @teamService.isTeamAdmin(#teamName, authentication.principal.id)")
//    public ResponseEntity<ApiResponse<TeamUserResponse>> addTeamUser(
//            @PathVariable String teamName,
//            @RequestParam Integer userId,
//            @RequestParam String identity,
//            Authentication authentication) {
//        try {
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
//            String enterpriseId = userDetails.getEnterpriseId();
//
//            TeamUser teamUser = teamService.addTeamUser(team.getTenantId(), userId, identity, enterpriseId);
//            User user = userRepository.findById(userId.longValue()).orElse(null);
//
//            return ResponseEntity.ok(ApiResponse.success(new TeamUserResponse(teamUser, user), "成员添加成功"));
//        } catch (Exception e) {
//            log.error("Failed to add team user: {} to team: {}", userId, teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
//
//    @PutMapping("/{teamName}/users/{userId}/identity")
//    @Operation(summary = "更新成员身份", description = "更新团队成员的身份")
//    @PreAuthorize("hasRole('ADMIN') or @teamService.isTeamAdmin(#teamName, authentication.principal.id)")
//    public ResponseEntity<ApiResponse<Void>> updateTeamUserIdentity(
//            @PathVariable String teamName,
//            @PathVariable Integer userId,
//            @RequestParam String identity) {
//        try {
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            teamService.updateTeamUserIdentity(team.getTenantId(), userId, identity);
//            return ResponseEntity.ok(ApiResponse.success(null, "成员身份更新成功"));
//        } catch (Exception e) {
//            log.error("Failed to update team user identity: {} in team: {}", userId, teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
//
//    @DeleteMapping("/{teamName}/users/{userId}")
//    @Operation(summary = "移除团队成员", description = "从团队中移除成员")
//    @PreAuthorize("hasRole('ADMIN') or @teamService.isTeamAdmin(#teamName, authentication.principal.id)")
//    public ResponseEntity<ApiResponse<Void>> removeTeamUser(
//            @PathVariable String teamName,
//            @PathVariable Integer userId) {
//        try {
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            teamService.removeTeamUser(team.getTenantId(), userId);
//            return ResponseEntity.ok(ApiResponse.success(null, "成员移除成功"));
//        } catch (Exception e) {
//            log.error("Failed to remove team user: {} from team: {}", userId, teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
//
//    @GetMapping
//    @Operation(summary = "获取团队列表", description = "获取当前用户的团队列表")
//    public ResponseEntity<ApiResponse<List<TeamResponse>>> getUserTeams(Authentication authentication) {
//        try {
//            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
//            Integer userId = userDetails.getId().intValue();
//
//            List<TeamUser> userTeams = teamService.getUserTeamRelations(userId);
//            List<TeamResponse> responses = userTeams.stream()
//                .map(teamUser -> {
////                    Team team = teamService.findByTenantId(teamUser.getTenantId()).orElse(null);
////                    return team != null ? new TeamResponse(team) : null;
//                    return new TeamResponse(null);
//                })
//                .filter(team -> team != null)
//                .collect(Collectors.toList());
//
//            return ResponseEntity.ok(ApiResponse.success(responses));
//        } catch (Exception e) {
//            log.error("Failed to get user teams", e);
//            return ResponseEntity.internalServerError()
//                .body(ApiResponse.error(500, "获取团队列表失败"));
//        }
//    }
//}
